package com.winai.launcher.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ks.projectbasictools.utils.LogUtils;
import com.thanosfisherman.wifiutils.wifiConnect.ConnectionErrorCode;
import com.winai.launcher.R;
import com.winai.launcher.base.BaseRecAdapter;
import com.winai.launcher.base.BaseRecViewHolder;
import com.winai.launcher.bean.WifiItemBean;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.manager.NetworkManager;
import com.winai.launcher.manager.WifiAutoConnectManager;
import com.winai.launcher.override.dialog_global.GlobalDialog;
import com.winai.launcher.utils.PicassoLoadUtils;
import com.winai.launcher.view.guide.ConfigWifiActivity;
import com.winai.launcher.view.set.SetWifiActionActivity;
import com.winai.launcher.view.set.SetWifiActivity;
import com.winai.launcher.view.set.SetWifiLinkActivity;

import java.util.Collections;

public class WifiItemAdapter extends BaseRecAdapter<WifiItemBean, WifiItemAdapter.ViewHolder> {
    private final WifiAutoConnectManager wifiAutoConnectManager;
    private Context mContext;
    private String comeFromActivity;

    public WifiItemAdapter(Context mContext, String comfromAct) {
        this.mContext = mContext;
        this.comeFromActivity = comfromAct;

        WifiManager mWifiManager = (WifiManager) mContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiAutoConnectManager = WifiAutoConnectManager.newInstance(mWifiManager);
    }

    @Override
    public void onHolder(ViewHolder holder, WifiItemBean wifiItemBean, int position) {
        View viewLine = holder.getView(R.id.view_line);
        TextView wifiName = holder.getView(R.id.tv_wifiName);
        TextView tvLinkState = holder.getView(R.id.tv_linkState);
        ImageView ivLinkState = holder.getView(R.id.iv_linkState);
        ImageView ivWifi = holder.getView(R.id.iv_wifi);

        int signalNumsLevel = WifiAutoConnectManager.getSignalNumsLevel(wifiItemBean.getLevel(), 3);
        int wifiLayout = 0;
        switch (signalNumsLevel) {
            case 2:
                wifiLayout = R.mipmap.icon_wifi_3;
                break;
            case 1:
                wifiLayout = R.mipmap.icon_wifi_2;
                break;
            case 0:
                wifiLayout = R.mipmap.icon_wifi_1;
                break;
        }
        PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(wifiLayout, ivWifi);

        String linkStatus = wifiItemBean.getLinkStatus();
        wifiName.setText(wifiItemBean.getWifiName());
        WifiAutoConnectManager.WifiCipherType wifiCipher = WifiAutoConnectManager.getWifiCipher(wifiItemBean.getWifiType());
        switch (linkStatus) {
            case WifiItemBean.LinkState.LINKED://已连接
                connected(linkStatus, tvLinkState, ivLinkState, R.mipmap.icon_wifi_linked);
                if (TextUtils.isEmpty(comeFromActivity) || !comeFromActivity.equals("ConfigWifiActivity")) {
                    viewLine.setVisibility(View.INVISIBLE);
                }
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new GlobalDialog.Builder(mContext)
                                .setTitle("是否忽略此网络")
                                .setContent("忽略此网络后，设备将断开此网络连接，并清空该网络密码！")
                                .setConfirmText("忽略")
                                .setCancelText("取消")
                                .setConfirmGradient(true)
                                .setCancelAble(true)
                                .setOnConfirmClickListener((mGlobalDialog, v1) -> {
                                    // 忽略WiFi，忘记网络
                                    wifiAutoConnectManager.removeWifiBySsid(wifiItemBean.getWifiName());
                                    NetworkManager.getInstance(mContext).setConnectedWifi(null);
                                    GlobalPublisher.Notify(GlobalPublisher.CHANGE_WIFI, 0);
                                }).show();
                    }
                });
                break;
            case WifiItemBean.LinkState.UNLINK://未连接
                viewLine.setVisibility(View.VISIBLE);
                if (wifiCipher == WifiAutoConnectManager.WifiCipherType.WIFICIPHER_NOPASS) {
                    connected(linkStatus, tvLinkState, ivLinkState, R.mipmap.icon_wifi_clock_open);
                } else {
                    connected(linkStatus, tvLinkState, ivLinkState, R.mipmap.icon_wifi_unlinked);
                }
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, SetWifiLinkActivity.class);
                        intent.putExtra("titleName", "连接无线网络");
                        intent.putExtra("WifiItemBean", wifiItemBean);
                        mContext.startActivity(intent);
                    }
                });
                break;
            case WifiItemBean.LinkState.SAVED://已保存:
                viewLine.setVisibility(View.VISIBLE);
                if (wifiCipher == WifiAutoConnectManager.WifiCipherType.WIFICIPHER_NOPASS) {
                    connected(linkStatus, tvLinkState, ivLinkState, R.mipmap.icon_wifi_clock_open);
                } else {
                    connected(linkStatus, tvLinkState, ivLinkState, R.mipmap.icon_wifi_unlinked);
                }
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, SetWifiActionActivity.class);
                        intent.putExtra("wifiItemBean", wifiItemBean);
                        if (mContext instanceof SetWifiActivity) {
                            ((SetWifiActivity) mContext).startActivityForResult(intent, Constant.RESULT_LINK_WIFI);
                        } else if (mContext instanceof ConfigWifiActivity) {
                            ((ConfigWifiActivity) mContext).startActivityForResult(intent, Constant.RESULT_LINK_WIFI);
                        }
                    }
                });
                break;
            case WifiItemBean.LinkState.LINKING://正在连接
                holder.itemView.setOnClickListener(null);
                connecting(linkStatus, tvLinkState, ivLinkState);
                break;
            default:
                break;
        }
    }

    @Override
    public ViewHolder onCreateHolder() {
        return new ViewHolder(getViewByRes(R.layout.item_wifi));
    }

    /**
     * 说明：展示加载中，正在连接
     */
    private void connecting(String linkStateStr, TextView linkState, ImageView imageView) {
        //showLoading
        linkState.setText(linkStateStr);
    }

    /**
     * 说明：完成加载中，已保存/未连接/已连接
     */
    private void connected(String linkStateStr, TextView linkState, ImageView imageView, int ivLayoutId) {
        if (linkState != null) {
            linkState.setText(linkStateStr);
            linkState.setTextColor(Color.parseColor("#585858"));
        }
        if (imageView != null) {
            imageView.setImageResource(ivLayoutId);
            imageView.clearAnimation();
        }
    }

    /**
     * 说明：置顶
     */
    public void onTop(WifiItemBean bean) {
        int pos = -1;
        for (int i = 0; i < getData().size(); i++) {
            if (getData().get(i).getWifiName().equals(bean.getWifiName())) {
                pos = i;
                break;
            }
        }
        if (pos == -1) {
            return;
        }
        Collections.swap(getData(), pos, 0);//两个元素交换位置
        notifyDataSetChanged();
    }

    class ViewHolder extends BaseRecViewHolder {
        ViewHolder(View itemView) {
            super(itemView);
        }
    }
}
